import { TBY } from '@/api/config/servicePort'
import http from '@/api'

/**附件关系命名空间 */
export namespace TbyFileBusiness {
  export interface Query {
    businessIdentifying: string
    businessId: number
  }

  export interface Form {
    id: number
    businessIdentifying: string
    businessId: number
    bucketName: string
    fileName: string
    fileId: string
    fileUrl: string
  }
}

/**
 * 查询附件
 * @param params：参数
 * @returns 结果
 */
export const listFileBusiness = (businessIdentifying: string, businessId: number) => {
  return http.get<TbyFileBusiness.Form[]>(TBY + `/file_business/list`, { businessIdentifying, businessId })
}

export const dateFormat = (millisecond: number, format: string) => {
  let resultDate = new Date(millisecond)
  let dateJson: any = {
    'y+': resultDate.getFullYear(),
    'M+': resultDate.getMonth() + 1,
    'd+': resultDate.getDate(),
    'H+': resultDate.getHours(),
    'm+': resultDate.getMinutes(),
    's+': resultDate.getSeconds()
  }
  for (let key in dateJson) {
    if (new RegExp('(' + key + ')').test(format)) {
      format = format.replace(RegExp.$1, (dateJson[key] + '').length < 2 ? '0' + dateJson[key] : dateJson[key])
    }
  }
  return format
}

export function convertBytes(bytes?: number) {
  if (bytes) {
    const units: string[] = ['B', 'KB', 'MB', 'GB']
    let unitIndex = 0
    while (bytes >= 1024 && unitIndex < units.length) {
      bytes /= 1024
      unitIndex++
    }
    return `${bytes.toFixed(2)} ${units[unitIndex]}`
  }
  return `0`
}

/**经度校验 */
export const validateLongitude = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const regExp = /^-?\d+(\.\d+)?$/
  if (value != '' && !regExp.test(value)) {
    callback(new Error('请输入有效的数字！'))
  } else {
    if (!checkDecimalMaxNum(value + '', 7)) {
      callback(new Error('小数点后最多七位小数'))
      return
    }
    let longitude = parseFloat(value)
    if (longitude > 180 || longitude < -180) {
      callback(new Error('经度范围在 -180 到 180 之间'))
    } else {
      callback()
    }
  }
}

/**纬度校验 */
export const validateLatitude = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const regExp = /^-?\d+(\.\d+)?$/
  if (value != '' && !regExp.test(value)) {
    callback(new Error('请输入有效的数字！'))
  } else {
    if (!checkDecimalMaxNum(value + '', 7)) {
      callback(new Error('小数点后最多七位小数'))
      return
    }
    let latitude = parseFloat(value)
    if (latitude > 90 || latitude < -90) {
      callback(new Error('纬度范围在 -90 到 90 之间'))
    } else {
      callback()
    }
  }
}

/**百分比数字验证 */
export const validatePercent = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  if (!checkDecimalMaxNum(value + '', 2)) {
    callback(new Error('最多支持两位小数'))
    return
  }
  const regExp = /^-?\d+(\.\d+)?$/
  if (!regExp.test(value)) {
    callback(new Error('请输入有效的数字！'))
    return
  }
  let num = parseFloat(value)
  if (num < 0 || num > 100) {
    callback(new Error('百分比只能在 0 到 100 之间'))
    return
  }
  callback()
}

/**两位小数验证 */
export const validateDecimalTwo = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  let str = value + ''
  if (str.length > 10) {
    callback(new Error('长度不能大于10'))
    return
  }
  if (!checkDecimalMaxNum(value + '', 2)) {
    callback(new Error('最多支持两位小数'))
    return
  }
  const regExp = /^-?\d+(\.\d+)?$/
  if (!regExp.test(value)) {
    callback(new Error('请输入有效的数字！'))
    return
  }
  callback()
}

/**两位小数验证,必须是大于等于0的数 */
export const validateDecimalTwoInteger = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  let str = value + ''
  if (str.length > 10) {
    callback(new Error('长度不能大于10'))
    return
  }
  if (!checkDecimalMaxNum(value + '', 2)) {
    callback(new Error('最多支持两位小数'))
    return
  }
  const regExp = /^\d+(\.\d+)?$/
  if (!regExp.test(value)) {
    callback(new Error('请输入大于等于0的有效的数字！'))
    return
  }
  callback()
}

/**验证整数 */
export const validateInteger = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  let str = value + ''
  if (str.length > 10) {
    callback(new Error('长度不能大于10'))
    return
  }
  const regExp = /^[0-9]*$/
  if (!regExp.test(value)) {
    callback(new Error('请输入大于等于0的整数'))
    return
  }
  callback()
}

export const validateIntegerMoreZero = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  let str = value + ''
  if (str.length > 10) {
    callback(new Error('长度不能大于10'))
    return
  }
  if (str.indexOf('0') === 0) {
    callback(new Error('请输入大于0的整数'))
    return
  }
  const regExp = /^[0-9]*$/
  if (!regExp.test(value)) {
    callback(new Error('请输入大于0的整数'))
    return
  }
  callback()
}

/**11位手机号验证 */
export const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const reg = /^[1][3-9][0-9]{9}$/
  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

export const checkDecimalMaxNum = (value: string, max: number) => {
  let array = value.split('.')
  if (array.length > 1) {
    if (array[1].length > max) {
      return false
    }
  }
  return true
}

export function exportExcel(url: string, params: any) {
  http.post(TBY + url, params, { responseType: 'arraybuffer' }).then((response: any) => {
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    const a = document.createElement('a')
    const href = window.URL.createObjectURL(blob)
    a.href = href
    a.download = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1])
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(href)
  })
}
